#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import time
import datetime
import os
import oauth
import simplejson
import urllib
import urllib2
import random
import sys
from init import *
"""

"""
class mixiGraphCallBack(webapp.RequestHandler):
    def get(self):
        c = consumer_keys("./lib/data/key.json")
        CONSUMER_KEY = c["mixi"][os.environ["SERVER_NAME"]]["consumer_key"]
        CONSUMER_SECRET_KEY = c["mixi"][os.environ["SERVER_NAME"]]["consumer_secret_key"]
        """grant_type    “authorization_code”
        client_id    Consumer key
        client_secret    Consumer secret
        code    Authorization Code
        redirect_uri    Redirect URI （サービス登録の際に入力したURIをそのまま指定します）"""
        url = 'https://secure.mixi-platform.com/2/token'
        token_params = {
                        'grant_type'    : 'authorization_code',
                        'client_id'     : CONSUMER_KEY,
                        'client_secret' : CONSUMER_SECRET_KEY,
                        'code'          : self.request.get("code"),
                        'redirect_uri'  : 'http://%s/redirect' % os.environ["HTTP_HOST"]
        }
        token_res = urllib.urlopen(
             url,
             urllib.urlencode(token_params).encode("utf-8")
             ).read()
        token_dic = simplejson.loads(token_res)
        memcache.set("mixi_oauth",token_dic)
        self.response.headers['Content-Type'] = 'text/html;charset=utf-8'
        # print token_res
        expires_date = datetime.datetime.utcnow() + datetime.timedelta(900)
        expires = expires_date.strftime("%d %b %Y %H:%M:%S GMT")
        for i in token_dic:
            self.response.headers.add_header('Set-Cookie', '%s=%s; expires=%s' % ("mixi_"+i, token_dic[i], expires))
            self.response.out.write('[%s] : %s\n<br>' % ("mixi_"+i, token_dic[i]))
        self.redirect('/')
        
class mixiGraphRefresh(webapp.RequestHandler):
    def __init__(self):
        self.keys=consumer_keys("./lib/data/key.json")
    
    def get(self):
        #mixi_refresh_token
        #cookies = self.request.cookies
        CONSUMER_KEY = self.keys["mixi"][os.environ["SERVER_NAME"]]["consumer_key"]
        CONSUMER_SECRET_KEY = self.keys["mixi"][os.environ["SERVER_NAME"]]["consumer_secret_key"]
        url = 'https://secure.mixi-platform.com/2/token'
        self.response.out.write(self.request.cookies.get("mixi_refresh_token",""))
        token_params = {
                        'grant_type'    : 'refresh_token',
                        'client_id'     : CONSUMER_KEY,
                        'client_secret' : CONSUMER_SECRET_KEY,
                        'refresh_token' : self.request.cookies.get("mixi_refresh_token","")
        }   
        token_res = urllib.urlopen(
             url,
             urllib.urlencode(token_params).encode("utf-8")
             ).read()
        token_dic = simplejson.loads(token_res)
        self.response.headers['Content-Type'] = 'aplication/json;charset=utf-8'
        #print token_res
        expires_date = datetime.datetime.utcnow() + datetime.timedelta(900)
        expires = expires_date.strftime("%d %b %Y %H:%M:%S GMT")
        for i in token_dic:
            #self.response.headers.add_header('Set-Cookie', '%s=%s; expires=%s' % (i, token_dic[i], expires))
            self.response.headers.add_header('Set-Cookie', '%s=%s; expires=%s' % ("mixi_"+i, token_dic[i], expires))
            #self.response.out.write('[%s] : %s\n<br>' % ("mixi_"+i, token_dic[i]))
            
        self.redirect('/')
        #self.response.out.write(token_res)
class RkTouchCallBack(webapp.RequestHandler):
    def __init__(self):
        self.keys=consumer_keys("./lib/data/key.json")
        self.client_id = self.keys["rktouch"]["localhost"]["client_id"]
        self.client_secret = self.keys["rktouch"]["localhost"]["client_secret"]
        self.callbackUrl = 'http://%s/rktch' % os.environ["HTTP_HOST"]
        self.tokenUrl = 'https://tou.ch/oauth2/token'# POST
        
    def get(self):
        token_params = {
            'grant_type'    : 'authorization_code',
            'client_id'     : self.client_id,
            'client_secret' : self.client_secret,
            'code'          : self.request.get("code"),
            'redirect_uri'  : self.callbackUrl
        }
        
        token_res = urllib.urlopen(
             self.tokenUrl,
             urllib.urlencode(token_params).encode("utf-8")
        ).read()
        json = simplejson.loads(token_res)
        # self.response.out.write("[%s] : %s\n<br>" % ("rktch_access_token", json["access_token"]))
        self.response.headers.add_header('Set-Cookie', '%s=%s; expires=%s' % ("rktch_access_token", json["access_token"], 10000))
        #self.response.out.write(self.request.cookies.get("rktch_access_token",""))
        self.redirect('/')

    def post(self):
        self.response.out.write("POST")

application = webapp.WSGIApplication([('/redirect', mixiGraphCallBack),
                                      ('/rktch', RkTouchCallBack),
                                      ('/refresh', mixiGraphRefresh)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
